package com.example.teach.config.interceptor;

import com.example.teach.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

public class JwtAuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的Authorization字段
        String authorization = request.getHeader("Authorization");

        //检查令牌格式是否正确(Bearer + 空格 + 令牌）
        if(authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);

            //验证令牌
            if(JwtUtil.validateToken(token)){
                //从令牌中获取用户名
                Integer userId = JwtUtil.getUserIdFromToken(token);
                String userName = JwtUtil.getUsernameFromToken(token);
                Integer userType = JwtUtil.getUserTypeFromToken(token);
                //设置认证信息到SecurityContext
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userId,userType,new ArrayList<>());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}